/**
 * @module geometry
 * @description
 * 这个模块包含了一些核心的、通用的几何运算函数，
 * 主要用于处理 `TerrainSchematic` 的坐标和边界。
 */

import type TerrainSchematic from "../schematic";

/**
 * 在操作后重新计算边界并归一化所有方块的坐标，确保蓝图始终从(0,0,0)开始。
 */
export function normalizeAndUpdateBounds(schematic: TerrainSchematic): void {
  if (schematic.schematicBlocks.length === 0) {
    schematic.data.bounds = new GameBounds3(
      new GameVector3(0, 0, 0),
      new GameVector3(-1, -1, -1)
    ); // 表示空
    return;
  }

  let minX = Infinity,
    minY = Infinity,
    minZ = Infinity;
  let maxX = -Infinity,
    maxY = -Infinity,
    maxZ = -Infinity;

  for (const block of schematic.schematicBlocks) {
    minX = Math.min(minX, block.x);
    minY = Math.min(minY, block.y);
    minZ = Math.min(minZ, block.z);
    maxX = Math.max(maxX, block.x);
    maxY = Math.max(maxY, block.y);
    maxZ = Math.max(maxZ, block.z);
  }

  const newSize = new GameVector3(
    maxX - minX + 1,
    maxY - minY + 1,
    maxZ - minZ + 1
  );

  // 归一化操作会移动局部坐标系的原点，因此需要更新世界原点
  schematic.origin.add(new GameVector3(minX, minY, minZ));

  for (const block of schematic.schematicBlocks) {
    block.x -= minX;
    block.y -= minY;
    block.z -= minZ;
  }

  schematic.data.bounds = new GameBounds3(
    new GameVector3(0, 0, 0),
    newSize.sub(new GameVector3(1, 1, 1))
  );
}
